
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "db/KeyDB.h"
#include "utils/StringUtils.h"

#define BROKERNAME "broker"

int main(int argc, char **argv)
{
   KeyDB *kdb = new KeyDB("client_keydb", "blah", NULL, "blah", 1);
   std::vector<char *> *allkeys1 = kdb->sqlScanAllTextf("select keyname from 'public_key';");
   std::vector<char *> *allkeys2 = kdb->sqlScanAllTextf("select keyname from 'public_key' where owner = '%s';", BROKERNAME);
   /*
   if ((allkeys1 != NULL) && (allkeys2 != NULL) && (allkeys1->size() != allkeys2->size()))
   {
      printf("Existing user data in client_keydb.sql, can not update broker key!\n");
      StringUtils::destroyStringList(allkeys1);
      StringUtils::destroyStringList(allkeys2);
      delete kdb;
      return 0;
   }
   */
   if ((allkeys1) && (allkeys1->size() > 0))
   {
      kdb->sqlInstantExecf("delete from 'public_key' where owner = '%s';", BROKERNAME);
      printf("Deleted older broker keys...\n");
   }
   if (allkeys1) StringUtils::destroyStringList(allkeys1);
   if (allkeys2) StringUtils::destroyStringList(allkeys2);
   FILE *FP;
   FP = fopen(argv[1], "rb");
   if (FP == NULL)
   {
      printf("Failed to open '%s' (is the broker running/do we have network?)\n", argv[1]);
      delete kdb;
      return 1;
   }
   fseek(FP, 0, SEEK_END);
   size_t lastpos = ftell(FP);
   fseek(FP, 0, SEEK_SET);
   char *keyname = (char *)malloc(sizeof(char)*(lastpos+1));
   fread(keyname, lastpos, 1, FP);
   keyname[lastpos] = '\0';
   fclose(FP);
   FP = fopen(argv[2], "rb");
   if (FP == NULL)
   {
      printf("Failed to open '%s' (is the broker running/do we have network?)\n", argv[2]);
      delete kdb;
      return 1;
   }
   fseek(FP, 0, SEEK_END);
   lastpos = ftell(FP);
   fseek(FP, 0, SEEK_SET);
   char *keydata = (char *)malloc(sizeof(char)*(lastpos+1));
   fread(keydata, lastpos, 1, FP);
   keydata[lastpos] = '\0';
   fclose(FP);
   kdb->AddPublicKey(keyname, "RSA", keydata, BROKERNAME);
   if (strlen(keyname) == 0)
   {
      printf("Could not write brokerkey to database (is the broker running/do we have network?)\n");
      delete kdb;
      return 1;
   }
   printf("Writing newest brokerkey '%s' to key database...\n", keyname);
   delete kdb;
   return 0;
}
